<template>
  <div class="app-container">
    <el-form ref="formRef" :disabled="!editAble" :model="form" :rules="rules" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="盘点编号" prop="inventoryCode">
            <div class="form-text">{{ form.inventoryCode }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="主题" prop="inventoryName">
            <el-tooltip effect="dark" :content="form.inventoryName">
              <div class="form-text">{{ form.inventoryName }}</div>
            </el-tooltip>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="工厂" prop="factory">
            <div class="form-text">{{ form.factoryName }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工段" prop="workSection">
            <div class="form-text">{{ form.workShopName }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产线" prop="pdcLine">
            <div class="form-text">{{ form.lineName }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工艺段" prop="processSection">
            <div class="form-text">{{ form.sectionName }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="线边仓" prop="storehouseName">
            <div class="form-text">{{ form.storehouseName }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="盘点日期" prop="inventoryDate">
            <el-tooltip effect="dark" :content="form.inventoryDate">
              <div class="form-text">
                {{ form.inventoryDate ? form.inventoryDate.join("至") : "" }}
              </div>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注" prop="remark">
            <div class="form-text">{{ form.remark }}</div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-tabs v-hasPermi="['warehouse:InventoryDetail:list']" v-model="activeName" class="demo-tabs">
      <el-tab-pane label="盘点明细" name="first">
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          label-width="100px"
          class="form-search"
        >
          <el-form-item label="物料/产品编号" prop="matCode">
            <el-input
              v-model="queryParams.matCode"
              placeholder="请输入物料/产品编号"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="物料/产品名称" prop="matName">
            <el-input
              v-model="queryParams.matName"
              placeholder="请输入物料/产品名称"
              @keyup.enter="handleQuery"
            />
          </el-form-item>

          <el-form-item label="批次号" prop="batchNo">
            <el-input
              v-model="queryParams.batchNo"
              placeholder="请输入批次号"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="类型" prop="matType">
            <el-tree-select
              v-model="queryParams.matType"
              :data="matTypes"
              :check-on-click-node="true"
              node-key="code"
              highlight-current
              filterable
              check-strictly
              :expand-on-click-node="false"
              :props="{ label: 'name', children: 'children' }"
              :render-after-expand="false"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="search" @click="handleQuery">查询</el-button>
            <el-button icon="refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-form ref="tableForm" :model="inventoryDetailList" label-width="0">
          <el-table
            v-loading="detailLoad"
            :data="inventoryDetailList"
            :row-class-name="rowIndexMethod"
            cell-class-name="table-form-item"
            border
            maxHeight="400"
            ref="whStorehouseInDetail"
            show-overflow-tooltip
          >
            <el-table-column label="序号" align="center" prop="index" width="80" />
            <el-table-column label="库位" prop="binCode"></el-table-column>
            <el-table-column label="物料/产品编码" prop="matCode"></el-table-column>
            <el-table-column label="物料/产品名称" prop="matName"></el-table-column>
            <el-table-column label="类型" prop="type"></el-table-column>
            <el-table-column label="单位" prop="packageUnit"></el-table-column>
            <el-table-column label="批次号" prop="batchNo"></el-table-column>
            <el-table-column label="当前库存" prop="num"></el-table-column>
            <el-table-column label="盘点库存" prop="inventoryNum"></el-table-column>

            <el-table-column label="偏差量" prop="inventoryOffset"></el-table-column>
            <el-table-column label="偏差原因" prop="inventoryOffsetReason"></el-table-column>
          </el-table>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup name="InventoryDetail">
import { getInventory, listDetail } from "@/api/warehouse/inventory";
import { getFactoryTree } from "@/api/system/dept";
import Decimal from "decimal.js";
import { ref, useAttrs, getCurrentInstance, reactive, toRefs, onMounted } from "vue";
import { queryMatTypeTree } from "@/api/base/material/MatTypeApi";

const attrs = useAttrs();
const { proxy } = getCurrentInstance();
const activeName = ref("first");
const matTypes = ref([]);
const refData = reactive({
  // 表单参数
  form: {},
  queryParams: {
    batchNo: "",
    matName: "",
    matCode: "",
    matTypeName: "",
  },
  // 表单校验
  rules: {
    inventoryCode: [{ required: true, message: "盘点编号不能为空", trigger: "blur" }],
    inventoryName: [{ required: true, message: "主题不能为空", trigger: "blur" }],
    factory: [{ required: true, message: "工厂不能为空", trigger: "blur" }],
    workSection: [{ required: true, message: "工段不能为空", trigger: "blur" }],
    pdcLine: [{ required: true, message: "产线不能为空", trigger: "blur" }],
    storehouseName: [{ required: true, message: "线边仓不能为空", trigger: "blur" }],
    inventoryDate: [{ required: true, message: "盘点日期不能为空", trigger: "blur" }],

    status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
  },
});
const { form, rules, queryParams } = toRefs(refData);
const emit = defineEmits(["close", "setActions", "setIsActionTop"]);
const inventoryDetailList = ref([]);

const formRef = ref("formRef");
const tableForm = ref("tableForm");
const editAble = ref(false);
const actions = ref([]);
const factoryOptions = ref([]);
const allTableData = ref([]);
function getFactorys() {
  getFactoryTree().then((res) => {
    factoryOptions.value = res.data;
  });
}
getFactorys();

/** 搜索按钮操作 */
function handleQuery() {
  filterSubTable();
}
function getMatType() {
  queryMatTypeTree().then((res) => {
    // formatTree(res.data)
    matTypes.value = res.data;
  });
}
getMatType();
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  filterSubTable();
}

function filterSubTable() {
  const result = [];
  allTableData.value.forEach((el) => {
    if (
      ((queryParams.value.matCode && el.matCode === queryParams.value.matCode) ||
        !queryParams.value.matCode) &&
      ((queryParams.value.matName && el.matName.includes(queryParams.value.matName)) ||
        !queryParams.value.matName) &&
      ((queryParams.value.batchNo && el.batchNo === queryParams.value.batchNo) ||
        !queryParams.value.batchNo) &&
      ((queryParams.value.matType && el.type === queryParams.value.matType) ||
        !queryParams.value.matType)
    ) {
      result.push(el);
    }
  });
  inventoryDetailList.value = result;
}

function getOffsetNum(num1, num2) {
  if (num1 === undefined || num1 === null || num1 === "") return "";
  return new Decimal(num1).minus(new Decimal(num2));
}
// 表单重置
function reset() {
  form.value = {
    inventoryCode: null,
    inventoryName: null,
    storehouseCode: null,
    storehouseName: null,
    inventoryDate: null,
    inventoryDoneDate: null,
    inventoryUserName: null,
    factory: null,
    workSection: null,
    pdcLine: null,
    processSection: null,
    remark: null,
  };
  formRef.value.resetFields();
  inventoryDetailList.value = [];
  allTableData.value = [];
}

/** 修改按钮操作 */
function getInventoryDetail(id) {
  getInventory(id).then((response) => {
    form.value = response.data;
    form.value.inventoryDate = form.value.inventoryDate ? form.value.inventoryDate.split("至") : [];
    if (proxy.checkPermi(["warehouse:InventoryDetail:list"])) {
      getSubDetail(form.value.inventoryCode);
    }
  });
}

function getSubDetail(inventoryCode) {
  listDetail({ pageSize: 10000, pageNum: 1, inventoryCode }).then((res) => {
    res.rows.forEach((el) => {
      el.num = el.stockNum;
      el.inventoryOffset = getOffsetNum(el.inventoryNum, el.stockNum);
    });
    allTableData.value = res.rows;
    inventoryDetailList.value = res.rows;
  });
}

/** 物料入仓明细序号 */
function rowIndexMethod({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

onMounted(() => {
  reset();
  const { data } = attrs;

  editAble.value = false;
  actions.value = [];
  emit("setActions", actions.value);

  if (data) {
    getInventoryDetail(data.mainTableId);
  }
});
</script>

<style lang="scss" scoped>
.redText {
  color: #f00 !important;
}
</style>
